package com.solace.selenium.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.excel.EasyExcel;
import com.solace.selenium.entity.Order;
import com.solace.selenium.service.WebDriverService;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.PlainText;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.List;

@Service
public class WebDriverServiceImpl implements WebDriverService {
    @Autowired
    private FirefoxDriver firefoxDriver;

    @Override
    public void findXpath(String xpath) {
        List<WebElement> elements = firefoxDriver.findElements(By.xpath(xpath));
        for (WebElement element : elements) {
            //element.click();
            try {
                WebElement dataKora = element.findElement(By.xpath("//a[@data-kora='查看敏感信息']/span"));
                dataKora.click();
                ThreadUtil.sleep(350);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getPageSource() {
        String pageSource = firefoxDriver.getPageSource();
        return pageSource;
    }

    @Override
    public Page createPage(String htmlStr, String currentUrl, String flag, String pageNum) {
        Page page = new Page();
        // 设置网页源码 + url
        page.setRawText(htmlStr);
        page.setUrl(new PlainText(currentUrl));
        page.isDownloadSuccess();

        // 设置request对象
        Request request = new Request(currentUrl);
        request.putExtra("level",flag);
        request.putExtra("pageNum",pageNum);
        page.setRequest(request);
        return page;
    }

    @Override
    public List<Order> parsingPage(Page page) {
        List<Order>  result = new ArrayList<>();
        Html html = page.getHtml();
        List<Selectable> nodes = html.$("div.index_tableRow__tpbkM.mortise-rich-table-row").nodes();
        for (Selectable node : nodes) {
            Order order = new Order();
            //订单号
            String orderId = node.$("div.index_content__3R2D9")
                    .replace("<div class=\"index_content__3R2D9\">\n", "")
                    .replace("订单号：", "")
                    .replace("<i data-kora=\"订单号复制\" class=\"index_copyIcon__1t5Aa\"></i>\n</div>", "").get().trim();
            System.out.println(orderId);
            order.setOrderId(orderId);
            String address = node.$("div.index_locationDetail__2IqFq")
                    .replace("<div class=\"index_locationDetail__2IqFq\">\n","")
                    .replace("<span class=\"index_icons__3PyVj\"><span data-kora=\"复制\" class=\"index_copyIconWrap__3obMY\">\n","")
                    .replace("<div class=\"flexibleCopy_content-wrapper__QAkVO\">\n","")
                    .replace("<span class=\"auxo-sp-icon sp-icon-parcel index_copyIcon__1zqrA\">\n","")
                    .replace("<svg class=\"icon\" aria-hidden=\"true\">\n","")
                    .replace("<use href=\"#icon-fuzhi\"></use>\n","")
                    .replace("<div class=\"index_viewIconWrapper__1pa53\">","")
                    .replace("</svg></span> \n","")
                    .replace("</div></span></span>\n","")
                    .replace("</div>","")
                    .get().trim();
            System.out.println(address);
            String[] split = address.split("，");
            order.setName(split[0]);
            order.setTel(split[1]);
            order.setAddress(split[2]);
            //订单号
            List<Selectable> orderTime = node.$("span.index_text__3y09K").nodes();
            String orderTimeStr = orderTime.get(1)
                    .replace("<span class=\"index_text__3y09K\">","")
                    .replace("</span>","").get();
            order.setOrderTime(orderTimeStr);
            //商品名字
            List<Selectable> goods = node.$("div.index_ellipsis__29MP5.undefined").nodes();
            String goodsStr=goods.get(0)
                    .replace("\n","")
                    .replace("<div class=\"index_ellipsis__29MP5 undefined\">","")
                    .replace("</div","").get()
            ;
            order.setGoods(goodsStr);
            String merchandiseStr=goods.get(1)
                    .replace("\n","")
                    .replace("<div class=\"index_ellipsis__29MP5 undefined\">","")
                    .replace("</div","").get()
                    ;
            order.setMerchandise(merchandiseStr);
            String talentNameStr=goods.get(2)
                    .replace("\n","")
                    .replace("<div class=\"index_ellipsis__29MP5 undefined\">","")
                    .replace("</div","").get()
                    ;
            String[] talentNameAndId = talentNameStr.split(" ");
            order.setTalentName(talentNameAndId[0]);
            order.setTalentId(talentNameAndId[1]);
            String goodsPrice = node.$("div.table_comboAmount__2Sohw").get()
                    .replace("\n","")
                    .replace("<div class=\"table_comboAmount__2Sohw\">","")
                    .replace("<span class=\"table_yuan__3Govr\">¥</span>","")
                    .replace("</div>","")
                    ;
            order.setGoodPrice(Double.valueOf(goodsPrice));

            //订单数量
            String goodsNumberStr = node.$("div.table_comboNum__1pAh5").get()
                    .replace("\n","")
                    .replace("<div class=\"table_comboNum__1pAh5\">","")
                    .replace("</div>","")
                    ;
            order.setGoodsNumber(goodsNumberStr);
            //支付方式
            order.setPayType("在线支付");
            //支付金额
            String payPriceStr = node.$("div.index_amountWrap__srYXC.index_marked__UM1dk").get()
                    .replace("\n","")
                    .replace("<div class=\"index_amountWrap__srYXC index_marked__UM1dk\"> <span class=\"index_yuan__330kS\">¥</span>","")
                    .replace("</div>","")
                    ;
            order.setOrderPrice(Double.valueOf(payPriceStr));
            //状态
            String status = node.xpath("//div[@style='display: flex;']/div[4]/div[1]").get()
                    .replace("<div>","")
                    .replace("</div>","")
                    ;
            order.setOrderStatus(status);
            //发货时间
           String deliveryTimeStr= node.$("div.table_timeout__2AfV9").get()
                   .replace("\n","")
                   .replace("<div class=\"table_timeout__2AfV9\">","")
                   .replace("</div>","")
                   ;
           order.setDeliveryTime(deliveryTimeStr);
            result.add(order);
        }
        return result;
    }

    @Override
    public void getPageSourceToPage() {
        String pageSource = firefoxDriver.getPageSource();
        createPage(pageSource, firefoxDriver.getCurrentUrl(),null,null);
    }

    @Override
    public String exportOrderList(String filePath) {
        if (!StringUtils.hasText(filePath)){
            return "未设置导出地址";
        }
        String fileName;
        try {
        String pageSource = firefoxDriver.getPageSource();
        Page page = createPage(pageSource, firefoxDriver.getCurrentUrl(), null, null);
        List<Order> orders = parsingPage(page);
        if (CollectionUtil.isEmpty(orders)){
            return "未获取到订单信息";
        }
        fileName = filePath+"/"+ System.currentTimeMillis() + ".xlsx";
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, Order.class).sheet("模板").doWrite(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return "导出EXCEL错误!";
        }
        return "导出位置:"+fileName;
    }
}
